package com.example.demo.model;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.example.demo.utils.JwtHelper;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
//        String token = request.getHeader("token");
        Enumeration<String> headers = request.getHeaders("Authorization");
        String token = headers.nextElement();
        System.out.println(token);
        if (token != null){
            boolean result = JwtHelper.verify(token);
            if(result){
                System.out.println("通过拦截器");
                return true;
            }
        }
        System.out.println("认证失败");
        Map<String,Object> map = new HashMap();
        map.put("code", 403);
        map.put("message","token过期，请重新登陆");
        response.getWriter().println(map);
        return false;
    }
}